<template>
  <transition v-if="visible">
    <div ref="moveModal" class="moveModal" :style="{ top: y + 'px', left: x + 'px', width: width }">
      <div class="moveHead" @mousedown="mousedown">
        {{ title }}
        <slot name="title"></slot>
      </div>
      <div class="close" @click="$emit('cancel')"><a-icon type="close" /></div>
      <div class="content">
        <!--插槽-->
        <slot></slot>
      </div>
      <slot name="footer"></slot>
    </div>
  </transition>
</template>

<script>
export default {
  props: {
    title: String,
    visible: {
      type: Boolean,
      default: false
    },
    width: {
      type: String,
      default: '500px'
    }
  },
  data() {
    return {
      x: 200, //left:x
      y: 100, //top:y
      isMove: false //是否移动标识
    }
  },
  watch: {
    visible(newVal, oldVal) {
      if (newVal) {
        let clientWidth = document.documentElement.clientWidth
        this.$nextTick(() => {
          let offsetWidth = this.$refs.moveModal.offsetWidth
          this.x = (clientWidth - offsetWidth) / 2
          this.y = 100
        })
      }
    }
  },
  methods: {
    mousedown(event) {
      // 鼠标按下事件
      this.isMove = true
      let windowH = window.innerHeight // 获取浏览器的可用高度
      let windowW = window.innerWidth // 获取浏览器的可用宽度

      document.onmousemove = e => {
        if (!this.isMove) return false
        let x = e.clientX - event.offsetX
        let y = e.clientY - event.offsetY
        if (x < 0 || x > windowW - 200 || y < 0 || y > windowH - 56) return false //当到达顶部或者底部时就不让继续拖动了

        this.x = x
        this.y = y
      }
      document.onmouseup = () => {
        this.isMove = false
        // 清除弹出框的移动事件及本身
        document.onmousemove = null
        document.onmouseup = null
      }
    }
  }
}
</script>

<style lang="less" scoped>
.moveModal {
  width: 500px;
  position: fixed;
  z-index: 99999;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0px 4px 15px 0px #c4c4c4;
  .moveHead {
    cursor: move;
    padding: 0 24px;
    color: rgba(0, 0, 0, 0.85);
    background: #fff;
    border-bottom: 1px solid #e8e8e8;
    border-radius: 4px 4px 0 0;
    font-size: 1.1rem;
    height: 56px;
    line-height: 56px;
    user-select: none;
  }
  .close {
    position: absolute;
    right: 0;
    top: 0;
    font-size: 16px;
    cursor: pointer;
    display: block;
    width: 56px;
    height: 56px;
    line-height: 56px;
    text-align: center;
    color: rgba(0, 0, 0, 0.45);
  }
  .close:hover {
    color: rgba(0, 0, 0, 0.7);
  }
  .content {
    padding: 24px;
    font-size: 1rem;
    line-height: 1.5;
    white-space: pre-line;
  }
}

.v-enter,
.v-leave-to {
  opacity: 0;
  transform: scale(0.5);
}
.v-enter-active,
.v-leave-active {
  transition: all 0.5s ease;
}
</style>
